package AIGUI;
//图片生成界面
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.image.Text2ImageResponse;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;

class GPICGUI {
    public void createAndShowGUI() {
        // 直接在代码中设置访问密钥和密钥
        String accessKey = "ALTAKtcDh0nQtP40NgZUAmDA4K";
        String secretKey = "57a949833c7b408a81e06959785d90cf";

        // 创建 Qianfan 实例
        Qianfan qianfan = new Qianfan(accessKey, secretKey);

        // 创建主窗口
        JFrame frame = new JFrame("生成图片");
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLayout(new BorderLayout());

        // 创建顶部面板用于输入提示词和生成按钮
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout());

        JLabel promptLabel = new JLabel("请输入提示词:");
        JTextField promptField = new JTextField(30);
        JButton generateButton = new JButton("生成");

        inputPanel.add(promptLabel);
        inputPanel.add(promptField);
        inputPanel.add(generateButton);

        frame.add(inputPanel, BorderLayout.NORTH);

        // 创建中央面板用于显示生成的图片
        JLabel imageLabel = new JLabel();
        JScrollPane imageScrollPane = new JScrollPane(imageLabel);
        frame.add(imageScrollPane, BorderLayout.CENTER);

        // 添加生成按钮的事件监听器
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String prompt = promptField.getText();
                try {
                    Text2ImageResponse response = qianfan.text2Image()
                            .prompt(prompt)
                            .execute();
                    String base64Image = response.getData().get(0).getB64Image();

                    // 解码并显示图片
                    byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                    ImageIcon imageIcon = new ImageIcon(imageBytes);
                    imageLabel.setIcon(imageIcon);

                    // 保存图片文件
                    String imageFilePath = "output_image.png";
                    try (OutputStream outputStream = new FileOutputStream(imageFilePath)) {
                        outputStream.write(imageBytes);
                        System.out.println("Image file saved to: " + imageFilePath);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        // 显示窗口
        frame.setVisible(true);
    }
}
